package com.leetcode.math;

/**
 * @author Dennis Li
 * @date 2020/7/30 19:47
 */
public class Reverse_7 {

    public int reverse(int x) {
        if (x == 0 || x == Integer.MAX_VALUE || x == Integer.MIN_VALUE) return 0;
        boolean negative = false;
        int temp = x;
        if (temp < 0) {
            temp = -temp;
            negative = true;
        }
        char[] array = String.valueOf(temp).toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = array.length - 1; i >= 0; i--) {
            if (sb.length() == 0 && array[i] == '0') continue;
            sb.append(array[i]);
        }
        try {
            return negative ? -Integer.parseInt(sb.toString()) : Integer.parseInt(sb.toString());
        } catch (Exception e) {
            return 0;
        }
    }

}
